package top.honlnk.common.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.honlnk.common.exception.CustomException;
import top.honlnk.service.PublicService;

import java.util.Objects;

@Slf4j
@Component
public class KeyInterceptor implements HandlerInterceptor {

    @Autowired
    private PublicService publicService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 1. 获取请求头中的key
        String key = request.getHeader("key");
        // 获取请求参数中的key
        if (StrUtil.isBlank(key)) {
            key = request.getParameter("key");
        }

        String path = request.getRequestURI();
        // 2. 判断是否为空，或者非法
        if (StrUtil.isBlank(key)) {
            log.info("path:{}", path);

            if (Objects.equals(path, "/api/user/upload")) {
                throw new CustomException("无key，小盆友，一定要带上自己的key再来上传课程表哦！");
            }
            if (Objects.equals(path, "/api/admin/update_rota")) {
                throw new CustomException("无key，小盆友，一定要带上自己的key再来修改值班表哦！");
            }
            if (Objects.equals(path, "/api/admin/produce_rota")) {
                throw new CustomException("无key，小盆友，一定要带上自己的key再来生成课程表哦！");
            }
            if (Objects.equals(path, "/api/get/rota")) {
                throw new CustomException("无key，小盆友，一定要带上自己的key再来获取值班表哦！");
            }
        }

        // 3. 获取key中的信息
        log.info("key:{}", key);
        // 判断传入的密钥是否合法，如果不合法，则抛出异常，反之继续执行后续操作，如果path中包含admin，则判断为管理员请求
        publicService.validateKey(key, path.contains("admin"));
        return true;
    }
}
